package com.example.wilson.music;


import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.wilson.music.http.LrcFileDownLoad;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class RankActivity extends Activity {

    private List<Music> music;
    private ListView rank_list;

    //热榜列表对象
    private ArrayList<Music> rankArrayList;
    private TextView title;

    private String data;
    private int rank_number;
    private String stringArray[];

    private AsyncRank asyncRank;
    private JSONArray jsonArray;
    private MediaPlayer player = new MediaPlayer();
    private int rank_status;
//    private StatusChangedReceiver receiver;

    public static final String RANK_URL = "http://api.bzqll.com/music/netease/songList?key=579621905&id=3778678&n=15";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rank);
        findViews();
        asyncRank = new AsyncRank();
        asyncRank.execute(LrcFileDownLoad.LRC_TENCENT_URL,"1232");
        registerListeners();
    }

    @Override
    protected void onStop() {
        super.onStop();
        player.stop();
    }

    /**
     * 获取显示组件
     */
    private void findViews(){
        rank_list = (ListView) findViewById(R.id.rank_musiclist);
        title = (TextView) findViewById(R.id.rank_title);

    }

    private void registerListeners(){
        rank_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.e("rank list","i:"+i);
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
                play(stringArray[i]);
//                if(rank_status == MusicService.STATUS_PLAYING){
//                    player.stop();
//                }else{
//                    rank_status = MusicService.STATUS_PLAYING;
//                    play(stringArray[i]);
//                }
            }
        });
    }

    /**
     * 发送命令，控制音乐播放。参数定义在MusicService中
     * @param command
     */
    private void sendBroadcastOnCommand(int command) {

        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同命令，封装不同的数据
        switch (command) {
            case MusicService.COMMAND_PLAY:
            case MusicService.COMMAND_SEEK_TO:
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }


    /**
     * 读取音乐文件
     * @param path
     */
    private void load(String path){
        try{
            player.reset();
            //此时并美誉真正的装在音频文件

                player.setDataSource(path);

            //还需要prepare去准备音频文件
            player.prepare();
        }catch ( Exception e){
            //TODO 显示对应的错误信息
            e.printStackTrace();
        }

        player.setOnCompletionListener(completionListener);
    }

    MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer player) {

        }
    };

    /**
     * 播放音乐
     * @param path
     */
    private void play(String path){
        //TODO 停止当前播放
        if(player != null && player.isPlaying()){
            player.stop();
        }
        load(path);
        player.start();
    }

    /**
     * 停止播放
     */
    private void stop(){
        if(rank_status != MusicService.STATUS_STOPPED){
            player.stop();
        }
    }

    class AsyncRank extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... strings) {
            data = LrcFileDownLoad.getHtmlCode(RANK_URL);
            try {
                JSONObject jsonObject = new JSONObject(data);
                JSONObject dataobj = jsonObject.getJSONObject("data");
                jsonArray = dataobj.getJSONArray("songs");

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return "200";
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            rankArrayList = MusicList.getMusicList();
            List<Map<String, String>> list_map_rank = new ArrayList<Map<String, String>>();
            HashMap<String, String> map;
            SimpleAdapter simpleAdapter;
            stringArray = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                map = new HashMap<String, String>();
                JSONObject job = null; // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                try {
                    job = jsonArray.getJSONObject(i);
                    map.put("musicName", job.getString("name"));
                    map.put("musicArtist", job.getString("singer"));
                    list_map_rank.add(map);
                    stringArray[i] = job.getString("url");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            String[] from = new String[] {"musicName", "musicArtist"};
            int[] to = {R.id.listview_tv_title_item, R.id.listview_tv_artist_item};
            simpleAdapter = new SimpleAdapter(RankActivity.this, list_map_rank, R.layout.listview, from, to);
            rank_list.setAdapter(simpleAdapter);
        }
    }
}
